package com.wdl.datarest.implementation;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 手环数据内存数据，主要用于拼接心率，高压低压，然后存入influx
 * 
 * @author Administrator
 *
 */
@Component
public class ShouHuanDataCache {

	private Map<String, ShouHuanData> shouHuanDataMap = new ConcurrentHashMap<String, ShouHuanData>();
	@Autowired
	private InfluxDBData influxDBData;

	public void updateHeartRate(String personId, String personName, String devId, short heartRate) {
		if (heartRate == 0) {
			return;
		}
		ShouHuanData d = shouHuanDataMap.get(devId);
		if (d == null) {
			d = new ShouHuanData();
			d.setDevId(devId);
			d.setHeartRate(heartRate);
			d.setIsSetHeartRate(true);
			shouHuanDataMap.put(devId, d);
		} else {
			d.setHeartRate(heartRate);
			d.setIsSetHeartRate(true);
			saveInfluxData(personId, personName, d);
		}
	}

	public void updateHlv(String personId, String personName, String devId, short hv, short lv) {

		if (hv == 0 || lv == 0) {
			return;
		}

		ShouHuanData d = shouHuanDataMap.get(devId);
		if (d == null) {
			d = new ShouHuanData();
			d.setDevId(devId);
			d.setHv(hv);
			d.setLv(lv);
			d.setIsSetHlv(true);
			shouHuanDataMap.put(devId, d);
		} else {
			d.setHv(hv);
			d.setLv(lv);
			d.setIsSetHlv(true);
			saveInfluxData(personId, personName, d);
		}
	}

	private void saveInfluxData(String personId, String personName, ShouHuanData d) {
		try {
			if (d.getIsSetHeartRate() && d.getIsSetHlv()) {
				Map<String, String> tags = new HashMap<>();
				Map<String, Object> fields = new HashMap<>();
				tags.put("personid", personId);
				tags.put("personname", personName);
				tags.put("devid", d.getDevId());

				fields.put("heart", d.getHeartRate());
				fields.put("hv", d.getHv());
				fields.put("lv", d.getLv());

				influxDBData.insert("heart_data", tags, fields);

				d.setIsSetHeartRate(false);
				d.setIsSetHlv(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
